<?php
// 请在安装了php+swoole的linux环境下用cli运行本客户端
// 这个客户端是测试TCP服务的
// 偷懒，直接用swoole的客户端写的，😁

go(function(){
    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);

    $client->set([
        'open_length_check'     => true,
        'package_length_type'   => 'N',
        'package_length_offset' => 0,       //第N个字节是包长度的值
        'package_body_offset'   => 4,       //第几个字节开始计算长度
        'package_max_length'    => 1024 * 1024,  //协议最大长度
    ]);

    // ------ 这里改成要连接的ip和端口 ------
    if(!$client->connect('127.0.0.1', 8086, 3))
    {
        exit("connect failed. Error: {$client->errCode}\n");
    }

    fwrite(STDOUT, 'connected' . PHP_EOL);
    fwrite(STDOUT, '请输入你的昵称：');

    $name = trim(fgets(STDIN));

    sendData($client, json_encode([
        'action'    =>    'login',
        'username'    =>    $name,
    ]));

    startMessageMonitor($client);
    startSendMonitor($client);
});

function startMessageMonitor($client)
{
    go(function() use($client){
        while(true)
        {
            $data = $client->recv();
            if(false !== $data)
            {
                $data = json_decode(substr($data, 4));
                switch($data->action)
                {
                    case 'login':
                        fwrite(STDOUT, '登录成功' . PHP_EOL);
                        break;
                    case 'send':
                        fwrite(STDOUT, '[' . date('Y-m-d H:i:s') . '] ' . $data->message . PHP_EOL);
                        break;
                }
            }
        }
    });
}

function startSendMonitor($client)
{
    go(function() use($client){
        if(SWOOLE_VERSION <= '4.0.3')
        {
            $message1 = '按两次回车编辑发送内容' . PHP_EOL;
            $message2 = '发送成功，按两次回车编辑发送内容' . PHP_EOL;
        }
        else
        {
            $message1 = '按回车编辑发送内容' . PHP_EOL;
            $message2 = '发送成功，按回车编辑发送内容' . PHP_EOL;
        }
        fwrite(STDOUT, $message1);
        while(true)
        {
            if(false === @Swoole\Coroutine::fgets(STDIN))
            {
                Swoole\Coroutine::fread(STDIN);
            }
            
            fwrite(STDOUT, '请输入你的内容：');

            $content = fgets(STDIN);
            
            $content = trim($content);

            sendData($client, json_encode([
                'action'    =>    'send',
                'message'    =>    $content,
            ]));
            fwrite(STDOUT, $message2);

        }
    });
}

function sendData($client, $data)
{
    $data = pack('N', strlen($data)) . $data;
    return $client->send($data);
}